package de.tum.icuproject.persistence.couchdb;

import com.google.gson.Gson;

import de.tum.icuproject.Subscriber;
import de.tum.icuproject.model.Player;
import de.tum.icuproject.persistence.PlayerRepository;
import de.tum.icuproject.persistence.couchdb.delete.DeleteRequestHandler;
import de.tum.icuproject.persistence.couchdb.insert.InsertRequestHandler;
import de.tum.icuproject.persistence.couchdb.select.IdGeneratorRequestHandler;
import de.tum.icuproject.persistence.couchdb.select.PlayerIdGeneratorRequestHandler;
import de.tum.icuproject.persistence.couchdb.select.SelectPlayerRequestHandler;
import de.tum.icuproject.persistence.couchdb.select.SelectRequestHandler;
import de.tum.icuproject.persistence.couchdb.update.UpdateRequestHandler;

/**
 * Implementation with CouchDB database
 * @author stefanoturchetta
 *
 */
public class PlayerRepositoryImpl implements PlayerRepository {
	
	private Subscriber subscriber;
	
	public PlayerRepositoryImpl(Subscriber subscriber) {
		this.subscriber = subscriber;
	}

	@Override
	public void findByPlayerId(int playerId) {
		String requestUrl = "players/_design/players/_view/by_playerId?key=" + playerId;
		SelectRequestHandler select = new SelectPlayerRequestHandler(this.subscriber);
		select.execute(requestUrl);
	}

	@Override
	public void insert(Player player) {
		String requestUrl = "players";
		String jsonData = new Gson().toJson(player, Player.class);
		InsertRequestHandler insert = new InsertRequestHandler(this.subscriber);
		insert.execute(requestUrl, jsonData);
	}
	
	@Override
	public void update(Player player) {
		String requestUrl = "players/" + player.get_id();
		String jsonData = new Gson().toJson(player, Player.class);
		UpdateRequestHandler update = new UpdateRequestHandler(this.subscriber);
		update.execute(requestUrl, jsonData);
	}

	@Override
	public void delete(Player player) {
		String requestUrl = "players/" + player.get_id() + "?rev=" + player.get_rev();
		DeleteRequestHandler delete = new DeleteRequestHandler(this.subscriber);
		delete.execute(requestUrl);
	}
	
	public void generatePlayerId() {
		// get the last used id
		String requestUrl = "players/_design/players/_view/by_playerId?descending=true&limit=1";
		IdGeneratorRequestHandler idGenerator = new PlayerIdGeneratorRequestHandler(this.subscriber);
		idGenerator.execute(requestUrl);
	}

}
